package com.rest.demo.functional.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * @author Administrator
 * @decription 原子操作
 * @Date 2018-01-31 10:13
 */
public class AtomicIntegerDemo {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        AtomicInteger atomicInteger = new AtomicInteger(0);
        IntStream.range(0,1000).forEach(i -> executor.submit(atomicInteger::incrementAndGet));
        ConcurrentUtils.stop(executor);
        System.out.println(atomicInteger);

        AtomicInteger atomicInt = new AtomicInteger(0);
        ExecutorService executor2 = Executors.newFixedThreadPool(2);
        IntStream.range(0,1000).forEach(i -> {
            Runnable task = () -> atomicInt.updateAndGet(n -> n + 2);
            executor2.submit(task);
        });
        ConcurrentUtils.stop(executor2);
        System.out.println(atomicInt.get());

        AtomicInteger atomicInt2 = new AtomicInteger();
        ExecutorService executor3 = Executors.newFixedThreadPool(3);
        IntStream.range(0,1000).forEach(
                i -> {
                    Runnable task = () -> atomicInt2.accumulateAndGet(i,(n,m) -> n + m);
                    executor3.submit(task);
                }
        );
        ConcurrentUtils.stop(executor3);
        System.out.println(atomicInt2.get());
    }
}
